package com.shire.shire_interface.controller.upload;

import com.shire.shire_interface.common.utils.MD5Util;
import com.shire.shire_interface.controller.BaseController;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//@Api(tags = "上传文件")
@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController {

//    @ApiOperation(value = "上传图片 mFile ,type:1:图片 2:文件 3:视频")
    @ResponseBody
    @PostMapping("/upload")
    public Map<String, Object> upLoad(MultipartFile mFile, Integer type, HttpSession session) {
        Map<String, Object> resultMap = new HashMap<>();
        try {

            if (!checkLoginUser(session)){
                resultMap.put("code", 501);
                resultMap.put("msg","请登录！");
                return resultMap;
            }

            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
            }

            String targetDir = "";
            if (type.equals(1)) {
                targetDir = "image";
            } else if (type.equals(2)) {
                targetDir = "file";
            } else if (type.equals(3)) {
                targetDir = "video";
            }
            Date date = new Date();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(targetDir);
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getYear());
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getMonth());
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getDate());
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getHours());


            targetDir = stringBuilder.toString();
            String dirPath = "static" + File.separator + targetDir + File.separator;
            File upload = new File(path.getAbsolutePath(), dirPath);
            if (!upload.exists()) {
                boolean mkdirs = upload.mkdirs();
            }
            String filename = mFile.getOriginalFilename();
            String ext = FilenameUtils.getExtension(filename);
            if (StringUtils.isBlank(ext))
                filename = FilenameUtils.getBaseName(filename);
            else
                filename = MD5Util.MD5Encode(FilenameUtils.getBaseName(filename)) +'.' + ext;
            String newFileName = System.currentTimeMillis() + "-" + filename;
            File uploadFile = new File(path.getAbsolutePath(), dirPath + newFileName);

            FileUtils.copyInputStreamToFile(mFile.getInputStream(), uploadFile);

            resultMap.put("msg", "成功");
            resultMap.put("code", 200);
            resultMap.put("resultPath", targetDir + File.separator + newFileName);
        } catch (Exception e) {
            resultMap.put("msg", "失败");
            resultMap.put("code", 500);
            resultMap.put("resultPath", "");
            e.printStackTrace();
        }
        return resultMap;
    }

   /* @ApiOperation(value = "读取 mFile ,type:1:图片 2:文件 3:视频")
    @RequestMapping("/file/{type}/{fileName}")
    public void downLoadFile(@PathVariable String fileName, @PathVariable Integer type, HttpServletResponse response) {

        String targetPath = "";
        if (type.equals(1)) {
            targetPath = imagePath;
        } else if (type.equals(2)) {
            targetPath = filePath;
        } else if (type.equals(3)) {
            targetPath = videoPath;
        }
        String filePath = targetPath + File.separator + fileName;

        File file = new File(filePath);
        FileInputStream in = null;
        OutputStream out = null;
        // 如果文件不存在
        if (!file.exists()) {
            System.out.println("您要下载的资源已被删除！！");
            return;
        }
        try {
            // 设置响应头，控制浏览器下载该文件
            response.setHeader("content-disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            // 读取要下载的文件，保存到文件输入流
            in = new FileInputStream(file);
            // 创建输出流
            out = response.getOutputStream();
            // 创建缓冲区
            byte buffer[] = new byte[1024];
            int len = 0;
            // 循环将输入流中的内容读取到缓冲区当中
            while ((len = in.read(buffer)) > 0) {
                // 输出缓冲区的内容到浏览器，实现文件下载
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                // 关闭文件输入流
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out) {
                // 关闭输出流
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/
}
